package com.sunkyc.framework.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunkyc.framework.system.CacheKey.SystemCacheKeys;
import com.sunkyc.framework.utils.RedisUtils;
import com.sunkyc.framework.system.entity.SysDictData;
import com.sunkyc.framework.system.mapper.SysDictDataMapper;
import com.sunkyc.framework.system.service.SysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author sunkyc
 * @since 2022-05-31
 */
@Service
@RequiredArgsConstructor
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {
    private final SysDictDataMapper baseMapper;
    private final RedisUtils redisUtils;



    @Override
    public List<SysDictData> queryByType(String dictType) {
        String key = SystemCacheKeys.DICT_DATA_TYPE+"_"+dictType;
        List<SysDictData> sysDictData = redisUtils.getCacheList(key);
        if(CollectionUtil.isNotEmpty(sysDictData)) return sysDictData;
        sysDictData = baseMapper.selectList(Wrappers.lambdaQuery(SysDictData.class).eq(SysDictData::getDictType, dictType).orderByAsc(SysDictData::getDictSort));
        if(CollectionUtil.isNotEmpty(sysDictData)) redisUtils.setCacheList(key,sysDictData);
        return sysDictData;
    }

    @Override
    public int addDictData(SysDictData sysDictData) {
        String key = SystemCacheKeys.DICT_DATA_TYPE+"_"+sysDictData.getDictType();
        int count = baseMapper.insert(sysDictData);
        if(count>0) redisUtils.deleteByPrefix(key);
        return count;
    }

    @Override
    public Boolean checkIsExistence(SysDictData sysDictData) {
        LambdaQueryWrapper<SysDictData> wrapper = Wrappers.lambdaQuery(SysDictData.class).eq(SysDictData::getDictType, sysDictData.getDictType())
                .eq(SysDictData::getDictValue, sysDictData.getDictValue());
        return baseMapper.exists(wrapper);
    }

    @Override
    public int updateDictData(SysDictData sysDictData) {
        String key = SystemCacheKeys.DICT_DATA_TYPE+"_"+sysDictData.getDictType();
        int count = baseMapper.updateById(sysDictData);
        if(count>0) redisUtils.deleteByPrefix(key);
        return count;
    }

    @Override
    public int deleteById(Long dictCode) {
        String key = SystemCacheKeys.DICT_DATA_TYPE+"_";
        int count = baseMapper.deleteById(dictCode);
        if(count>0) redisUtils.deleteByPrefix(key);
        return count;
    }
}
